const jwt = require('jsonwebtoken')
const config = require('../config/config.js')

class Auth {
  constructor(){}
  get check(){
    return async(ctx,next) => {
      let url = ctx.request.url;
      if (url == "/login") await next();
      else {
        if(ctx.request.header['authorization']){
          let token = ctx.request.header['authorization'];
          let decoded = jwt.decode(token, config.security.secretKey);
          if(token && decoded.exp <= new Date()/1000){
            ctx.status = 401;
            ctx.body = {
              code:1,
              msg: 'token过期'
            };
          }else{
            //如果权限没问题，那么交个下一个控制器处理
            return next();
          }
        } else{
            ctx.status = 401;
            ctx.body = {
              code:1,
              msg: '请带上token'
          }
        }
      }
    }
  }
}

class Cors {
  constructor(){}
  get cor(){
    return async(ctx,next) => {
      ctx.set("Access-Control-Allow-Origin", "*")
      // ctx.set("Access-Control-Allow-Headers", "X-Requested-With")
      ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
      ctx.set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
      await next()
    }
  }
}

module.exports = {
  Auth,Cors
}

// module.exports = function() {
//   return async function check(ctx, next) {
//     let url = ctx.request.url;
//     console.log(url)
//     // 登录 不用检查
//     if (url == "/login") await next();
    // else {
    //   if(ctx.request.header['authorization']){
    //     let token = ctx.request.header['authorization'];
    //     //解码token
    //     let decoded = jwt.decode(token, secret);
    //     if(token && decoded.exp <= new Date()/1000){
    //         ctx.status = 401;
    //         ctx.body = {
    //           message: 'token过期'
    //         };
    //     }else{
    //         //如果权限没问题，那么交个下一个控制器处理
    //         return next();
    //     }
    //   } else{
    //       ctx.status = 401;
    //       ctx.body = {
    //         message: '没有token'
    //     }
    //   }
    // }
//   }
// }